package com.mlog.njyjy.ndop.common.support;

import cn.hutool.core.util.ReUtil;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

/**
 * <p>
 *
 * </p>
 *
 * @author zyz
 * @version v1.0, 2020/8/17
 */
public class LocalDateTimeTypeAdapter extends TypeAdapter<LocalDateTime> {

    private static final Pattern SQL_DATE_PATTERN = Pattern.compile("^(\\d{4}-\\d{2}-\\d{2})T(\\d{2}:\\d{2}:\\d{2}).*");

    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void write(JsonWriter out, LocalDateTime value) throws IOException {
        if (value == null) {
            out.setSerializeNulls(false);
            out.nullValue();
        } else {
            out.value(value.format(dtf));
        }
    }

    @Override
    public LocalDateTime read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        String value = in.nextString();
        if (ReUtil.isMatch(SQL_DATE_PATTERN, value)) {
            value = String.join(" ", ReUtil.getAllGroups(SQL_DATE_PATTERN, value, false));
        }
        return LocalDateTime.parse(value, dtf);
    }
}
